package com.java.project.system.oss.controller;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.java.common.cloud.CloudConstant;
import com.java.common.cloud.CloudStorageConfig;
import com.java.common.cloud.OSSFactory;
import com.java.common.cloud.service.CloudStorageService;
import com.java.common.cloud.valdator.AliyunGroup;
import com.java.common.cloud.valdator.LocalGroup;
import com.java.common.cloud.valdator.QcloudGroup;
import com.java.common.cloud.valdator.QiniuGroup;
import com.java.common.utils.security.ShiroUtils;
import com.java.common.utils.tool.ValidatorUtils;
import com.java.project.system.config.service.IConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.java.framework.aspectj.lang.annotation.Log;
import com.java.framework.aspectj.lang.enums.BusinessType;
import com.java.project.system.oss.domain.Oss;
import com.java.project.system.oss.service.IOssService;
import com.java.framework.web.controller.BaseController;
import com.java.framework.web.domain.AjaxResult;
import com.java.common.utils.poi.ExcelUtil;
import com.java.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传Controller
 *
 * @author admin_wjz
 * @date 2019-11-12
 */
@Controller
@RequestMapping("/system/oss")
public class OssController extends BaseController {
    private String prefix = "system/oss";

    private final static String KEY = CloudConstant.CLOUD_STORAGE_CONFIG_KEY;

    @Autowired
    private IOssService ossService;

    @Autowired
    private IConfigService configService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept() {
        return prefix + "/oss";
    }

    /**
     * 查询文件上传列表
     */
    @RequiresPermissions("system:oss:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Oss oss) {
        startPage();
        List<Oss> list = ossService.selectOssList(oss);
        return getDataTable(list);
    }

    /**
     * 云存储配置信息
     */
    @RequestMapping("config")
    @RequiresPermissions("sys:oss:config")
    public String config(Model model) {
        String jsonconfig = configService.selectConfigByKey(CloudConstant.CLOUD_STORAGE_CONFIG_KEY);
        // 获取云存储配置信息
        CloudStorageConfig config = JSON.parseObject(jsonconfig, CloudStorageConfig.class);
        model.addAttribute("config", config);
        return prefix + "/config";
    }

    /**
     * 保存云存储配置信息
     */
    @RequestMapping("saveConfig")
    @RequiresPermissions("sys:oss:config")
    @ResponseBody
    public AjaxResult saveConfig(CloudStorageConfig config) {
        // 校验类型
        ValidatorUtils.validateEntity(config);
        if (config.getType() == CloudConstant.CloudService.LOCAL.getValue()) {
            // 校验本地数据
            ValidatorUtils.validateEntity(config, LocalGroup.class);
        } else if (config.getType() == CloudConstant.CloudService.QINIU.getValue()) {
            // 校验七牛云数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == CloudConstant.CloudService.ALIYUN.getValue()) {
            // 校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == CloudConstant.CloudService.QCLOUD.getValue()) {
            // 校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }
        return toAjax(configService.updateValueByKey(KEY, new Gson().toJson(config)));
    }

    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    @RequiresPermissions("sys:oss:add")
    @ResponseBody
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws Exception
    {
        if (file.isEmpty())
        {
            throw new RuntimeException("上传文件不能为空");
        }
        // 上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(file);
        // 保存文件信息
        Oss ossEntity = new Oss();
        ossEntity.setUrl(url);
        ossEntity.setFileSuffix(suffix);
        ossEntity.setCreateBy(ShiroUtils.getLoginName());
        ossEntity.setFileName(fileName);
        ossEntity.setCreateTime(new Date());
        ossEntity.setService(storage.getService());
        return toAjax(ossService.insertOss(ossEntity));
    }

    /**
     * 修改文件上传
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Oss oss = ossService.selectOssById(id);
        mmap.put("oss", oss);
        return prefix + "/edit";
    }

    @GetMapping("editor")
    @RequiresPermissions("sys:oss:add")
    public String editor() {
        return prefix + "/editor";
    }

    /**
     * 修改保存文件上传
     */
    @RequiresPermissions("system:oss:edit")
    @Log(title = "文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Oss oss) {
        return toAjax(ossService.updateOss(oss));
    }

    /**
     * 删除文件上传
     */
    @RequiresPermissions("system:oss:remove")
    @Log(title = "文件上传", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ossService.deleteOssByIds(ids));
    }
}
